
package com.sword.pay.spring;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sword.common.strategy.ISCommonStrategy;
import com.sword.common.utils.StrUtil;
import com.sword.pay.PayManager;
import com.sword.pay.repository.config.ISPayClientConfig;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * 组件注入注入 所需要的 Bean
 * src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
 * 是 Spring Boot 2.7+ 中引入的一种新的 自动配置加载机制
 */
public class SwordBeanInject {

	/**
	 * 注入设备Bean
	 * 
	 * @param repository 实现对象
	 */
	@Autowired(required = false)
	public void setISInvoiceDriverRepository(List<ISCommonStrategy> repository) {
		if(repository!=null){
			repository.forEach(bean ->	PayManager.setISInvoiceDriverRepository(bean));
		}
	}

	/**
	 * 注入配置类
	 *
	 * @param repository 实现对象
	 */
	@Autowired(required = false)
	public void setConfigBean(List<ISPayClientConfig> repository) {
		if(repository!=null){
			repository.forEach(bean ->	PayManager.setBeanConfig(bean));
		}
	}

	/**
	 * 配置文件获取创建配置信息
	 * @param drivers 配置类
	 */

	@Autowired(required = false)
	public void setConfigBeans(Map<String, Map<String, Object>> drivers) {
		for (String configId : drivers.keySet()) {
			Map<String, Object> configMap = drivers.get(configId);
			configMap.put("config-id", configId);
			// 如果开发者引入的是：sa-token-redis
			StrUtil.replaceKeysSeparator(configMap, "-", "_");
			JSONObject configJson = new JSONObject(configMap);

			try {
				Object clazz = configMap.get("class");
				Class<ISPayClientConfig> newClass = (Class<ISPayClientConfig>) Class.forName(clazz.toString());
				if (newClass == null) {
					System.out.println("未找到设备为");
					continue;
				}
				ISPayClientConfig payConfigInterface = newClass.newInstance();
				Class configClass = payConfigInterface.getConfigClass();
				ISPayClientConfig bean = (ISPayClientConfig) JSONUtil.toBean(configJson, configClass);

				PayManager.setBeanConfig(bean);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
